import { useState, useEffect } from "react";
import menus from "@/routers/menus";
import { Layout, Menu, Image } from "antd";
import { useSelector } from "react-redux";
import { useLocation, useNavigate } from "react-router-dom";
const { Sider } = Layout;

const rootSubmenuKeys = [];
menus.forEach((menu) => menu.children && rootSubmenuKeys.push(menu.key));
export default function AppSideBar() {
  const collapsed = useSelector((state) => state.appSlice.collapsed);
  const navigate = useNavigate();

  const { pathname } = useLocation();
  const [selectedKeys, setSelectedKeys] = useState([pathname]);
  const getSubMenu = (pathname) => {
    return pathname
      .split("/")
      .slice(1)
      .reduce(
        (prev, curr, index) => {
          prev.push(prev[index] + "/" + curr);
          return prev;
        },
        [""]
      )
      .slice(1);
  };
  const [openKeys, setOpenKeys] = useState(getSubMenu(pathname));
  const onOpenChange = (keys) => {
    const latestOpenKey = keys.find((key) => openKeys.indexOf(key) === -1);
    if (rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
      setOpenKeys(keys);
    } else {
      setOpenKeys(latestOpenKey ? [latestOpenKey] : []);
    }
  };
  // 检测点击面包屑导航，更改selectedKeys & openKeys
  useEffect(() => {
    // selectedKeys 当前选中的菜单项 key 数组
    setSelectedKeys([pathname]);
    // openKeys	当前展开的 SubMenu 菜单项 key 数组
    setOpenKeys(getSubMenu(pathname));
  }, [pathname]);
  const changeUrl = ({ key }) => {
    setSelectedKeys([key]);
    navigate(key);
  };
  return (
    <Sider trigger={null} collapsible collapsed={collapsed}>
      <div className="logo">
        <Image src="/logo.png" preview={false} />
      </div>
      <Menu
        theme="dark"
        mode="inline"
        openKeys={openKeys}
        selectedKeys={selectedKeys}
        onOpenChange={onOpenChange}
        items={menus}
        onClick={changeUrl}
      />
    </Sider>
  );
}
